import React, { useEffect, useState } from 'react'
import { message, Modal, Table } from 'antd'
import { ColumnType } from 'antd/lib/table';
import moment from 'moment'
import _ from 'lodash'
import { awaitWrap } from '@js/tool'
import { getElectronicResultRequest } from './ajax'
import Footer from '../footer'
import { updateServiceRequest } from './ajax'
import { ServiceResultSchema, ServiceTopicSchema } from '@src/components/schema/service'
// import style from './Modal.module.less'

function getColumns (): Array<ColumnType<ServiceResultSchema>> {
  return [
    {
      key: 'orderno',
      dataIndex: 'orderno',
      title: '序号',
      align: 'center'
    },
    {
      key: 'address',
      dataIndex: 'address',
      title: '地址'
    },
    {
      key: 'to_type',
      dataIndex: 'to_type',
      title: '类型',
      render: (v: string) => {
        if (v === 'mobile') {
          return '手机号'
        }
        if (v === 'email') {
          return '邮箱'
        }
      }
    },
    {
      key: 'status',
      dataIndex: 'status',
      title: '状态'
    },
    {
      key: 'create_datetime',
      dataIndex: 'create_datetime',
      title: '发送时间',
      width: 180,
      render: (v: number) => {
        if (v) {
          return moment(v * 1000).format('YYYY-MM-DD HH:mm:ss')
        }
      }
    }
  ]
}

// 获取送达结果数据
async function getElectronicResult (id: string, setDataSource: (v: ServiceResultSchema[]) => void) {
  const hide = message.loading('加载中', 120)
  const [e, d] = await awaitWrap(getElectronicResultRequest(id))
  hide()
  if (e === null && d !== null) {
    (d || []).forEach((li, i) => {
      li.orderno = i + 1
    })
    setDataSource(d)
  }
}

// 更新送达状态
async function updateStatus (d: {[k: string]: any}, data: {[k: string]: any}, hide: () => void, refreshCurrentTableFn: () => void) {
  const h = message.loading('提交中', 120)
  d = _.cloneDeep(d)
  const id = d.id
  delete d.id
  d.status = data.status
  d.status_ex = data.status_ex
  d.remark = data.remark
  d.arrive_datetime = Math.floor(data.arrive_datetime.valueOf() / 1000)
  const [e] = await awaitWrap(updateServiceRequest(id, d))
  h()
  if (e === null) {
    hide()
    refreshCurrentTableFn()
  }
}

interface Props {
  visible: boolean
  hide: () => void
  editable: boolean
  theme: ServiceTopicSchema
  refreshCurrentTableFn: () => void
  data: {[k: string]: any} | null
}

function Main ({ visible, hide, editable, theme, refreshCurrentTableFn, data }: Props) {
  const [datasource, setDataSource] = useState<ServiceResultSchema[]>([])
  const [modifiable, setModifiable] = useState(false)
  useEffect(() => {
    if (data && theme && visible) {
      setModifiable((editable && !theme.complete_datetime) && ['送达', '视为送达', '送达失败'].indexOf(data.status) === -1)
    }
  }, [data, visible, editable, theme])
  useEffect(() => {
    if (data && visible) {
      getElectronicResult(data.id, setDataSource)
    }
  }, [data, visible])
  useEffect(() => {
    if (!visible) {
      setDataSource([])
    }
  }, [visible])
  if (!data) {
    return <span />
  }
  return (
    <Modal
      visible={visible}
      title='发送情况'
      width={800}
      onCancel={hide}
      footer={<Footer readOnly={!modifiable} data={data} hide={hide} finishStatus={d => updateStatus(data, d, hide, refreshCurrentTableFn)} />}
      maskClosable={false}
      destroyOnClose
    >
      <Table rowKey='id' columns={getColumns()} dataSource={datasource} pagination={false} size='small' />
    </Modal>
  )
}

export default Main
